<script>
export default {
  methods: {
    selectSession(id) {
      this.$store.commit("SELECT_SESSION", id);
    }
  },
  computed: {
    sessions() {
      let filterKey = this.$store.state.messageCenter.filterKey;
      let sessions = this.$store.state.messageCenter.sessions;
      let result = sessions.filter(session =>
        session.sourceName.includes(filterKey)
      );
      return result;
    },
    currentId() {
      return this.$store.state.messageCenter.currentSessionId;
    },
    unread() {
      return function(items) {
        return (
          (items.messageList &&
            items.messageList.filter(item => item.status == 1).length) ||
          0
        );
      };
    },
    lastMsg() {
      return function(source) {
        let sessions = this.$store.state.messageCenter.sessions;
        let messageList =
          sessions.find(item => item["source"] === source)["messageList"] || [];
        let unreadList = messageList.filter(item => item.status * 1 !== 2);
        let lastMsg = (unreadList && unreadList[0]) || { title: null };
        return lastMsg["title"];
      };
    }
  }
};
</script>

<template>
  <div class="list">
    <ul v-if="sessions.length>0">
      <li
        v-for="item in sessions"
        :key="item.source"
        :class="{ active: item.source === currentId }"
        @click="selectSession(item.source)"
      >
        <a-badge
          :offset="[-3,0]"
          :numberStyle="{'transform': 'translate(50%, -50%) scale(0.8)'}"
          :count="unread(item)"
          :overflowCount="999"
        >
          <img
            class="avatar"
            :style="`background:${item['bgColor']}`"
            width="40"
            height="40"
            :alt="item.sourceName"
            :src="item.icon"
          >
        </a-badge>

        <div class="name">
          <span>{{item.sourceName}}</span>
          <h6 class="nowrap-1" v-if="lastMsg(item.source)">{{lastMsg(item.source)}}</h6>
        </div>
      </li>
    </ul>
  </div>
</template>

<style scoped lang="less">
.list {
  width: 100%;
  overflow: hidden;
  li {
    padding: 15px;
    cursor: pointer;
    list-style: none;
    border-bottom: 1px solid #eee;
    position: relative;
    &:hover {
      background: rgba(100, 123, 252, 0.04);
    }
    &.active {
      background: rgba(100, 123, 252, 0.08);
    }
  }
  .avatar,
  .name {
    vertical-align: middle;
    color: #333333;
  }
  .avatar {
    border-radius: 4px;
    padding: 8px;
  }
  .name {
    display: inline-block;
    margin: 0 0 0 6px;
    width: 160px;
    h6 {
      color: #666666;
      margin-bottom: 0;
    }
  }
}
</style>